const PrinterJobs = require('../printer/printerjobs.js')
const printerUtil = require('../printer/printerutil.js')
import printConfigList from '@/common/printConfig.js';

/**
 * @param {Object} ruleState是否启用条码规则
 * @param {Object} barCodeRelus条码规则的对象
 * @param {Object} searchKey搜索的字符串
 */
export function getRulesStr(ruleState, barCodeRelus, searchKey) {
	let finalObj = {
		SeparateIsEnable: 2,
		barRulesList: [],
		searchKey: searchKey,
		Inventorybatch: ""
	}
	if (ruleState) {
		if (barCodeRelus.Separate_IsEnable == 1) {
			finalObj.SeparateIsEnable = 0;
			if (barCodeRelus.Rule_Separate != "") {
				finalObj.barRulesList = searchKey.split(barCodeRelus.Rule_Separate);
				// console.log(parseFloat(this.barCodeRelus.Rule_Bar));
				if (parseInt(barCodeRelus.Rule_Bar) <= finalObj.barRulesList.length) {
					// console.log(this.barRulesList[parseInt(this.barCodeRelus.Rule_Bar)]);
					finalObj.searchKey = finalObj.barRulesList[parseInt(barCodeRelus.Rule_Bar) - 1];
				} else {
					finalObj.searchKey = searchKey;
				}
				if (parseInt(barCodeRelus.Rule_BatchNo) <= finalObj.barRulesList.length) {
					finalObj.Inventorybatch = finalObj.barRulesList[parseInt(barCodeRelus.Rule_BatchNo) - 1];
				}
			}
		}
		// 截取规则
		else if (barCodeRelus.Cut_IsEnable == 1) {
			finalObj.SeparateIsEnable = 1;
			console.log(barCodeRelus.BarRule_All_Length, searchKey.length);
			if (barCodeRelus.BarRule_All_Length == searchKey.length && searchKey != "") {
				if (barCodeRelus.BarRule_CutBar_Start != "" && barCodeRelus.BarRule_CutBar_End != "") {
					// barCodeStart = this.barCodeRelus.BarRule_CutBar_Start;
					finalObj.searchKey = searchKey.substring(parseInt(barCodeRelus.BarRule_CutBar_Start) - 1, barCodeRelus
						.BarRule_CutBar_End);
				} else {
					finalObj.searchKey = searchKey;
				}
				if (barCodeRelus.BarRule_CutBatchNo_Start != "" && barCodeRelus.BarRule_CutBatchNo_End != "") {
					// barCodeStart = this.barCodeRelus.BarRule_CutBar_Start;
					finalObj.Inventorybatch = searchKey.substring(parseInt(barCodeRelus.BarRule_CutBatchNo_Start) - 1, barCodeRelus
						.BarRule_CutBatchNo_End);
				}
			} else {
				finalObj.searchKey = searchKey;
			}
		} else {
			finalObj.SeparateIsEnable = 2;
			finalObj.searchKey = searchKey;
		}
	}
	return finalObj;
}

/**
 * @param {Object} SeparateIsEnable 启用的规则
 * @param {Object} barCodeRelus 条码规则
 * @param {Object} barRulesList 分割的数组
 // * @param {Object} res 源数组
 // * @param {Object} searchKey 搜索的条件
 // * @param {Object} searchKey 循环的索引
 */
export function ruleFinalRes(SeparateIsEnable, barCodeRelus, barRulesList, res, searchKey, index) {
	let resultObj = {
		result: res,
		isChange: true
	}
	if (SeparateIsEnable == 0) {
		console.log("分割规则");
		console.log(barCodeRelus);
		if (barCodeRelus.Rule_Num != "" && parseInt(barCodeRelus.Rule_Num) <= barRulesList.length) {
			res.data.ResultMsg[index].Qty = barRulesList[parseInt(barCodeRelus.Rule_Num) - 1];
			if (barCodeRelus.Rule_Num_Demical != "" && parseInt(barCodeRelus.Rule_Num_Demical) <= barRulesList
				.length) {
				var temp = 10;
				for (var i in barCodeRelus.Rule_Num_Demical) {
					temp *= 10;
				}
				console.log("temp", parseInt(barCodeRelus.Rule_Num_Demical))
				res.data.ResultMsg[index].Qty = res.data.ResultMsg[index].Qty / temp;
			}
		}

		if (barCodeRelus.Rule_Price != "" && parseInt(barCodeRelus.Rule_Price) <= barRulesList.length) {
			res.data.ResultMsg[index].Price = barRulesList[parseInt(barCodeRelus.Rule_Price) - 1];
			if (barCodeRelus.Rule_Price_Demical != "" && parseInt(barCodeRelus.Rule_Price_Demical) <= barRulesList
				.length) {
				var temp = 10;
				for (var i in barCodeRelus.Rule_Price_Demical) {
					temp *= 10;
					console.log(i);
				}
				res.data.ResultMsg[index].Price = res.data.ResultMsg[index].Price / temp;
			}
		} else {
			resultObj.isChange = false;
			// if (that.BillType == 1) {
			// 	res.data.ResultMsg[index].Price = res.data.ResultMsg[index].InPrice;
			// } else {
			// 	res.data.ResultMsg[index].Price = res.data.ResultMsg[index].SalePrice;
			// }
		}
	} else if (SeparateIsEnable == 1) {
		console.log("截取规则");
		// console.log(this.searchKey);
		// console.log(this.barCodeRelus);
		if (barCodeRelus.BarRule_All_Length == searchKey.length) {
			if (barCodeRelus.BarRule_CutNum_Start != "" && barCodeRelus.BarRule_CutNum_End != "" &&
				parseInt(barCodeRelus.BarRule_CutNum_Start) <= parseInt(barCodeRelus.BarRule_CutNum_End)) {
				res.data.ResultMsg[index].Qty = searchKey.substring(parseInt(barCodeRelus.BarRule_CutNum_Start) - 1,
					parseInt(barCodeRelus.BarRule_CutNum_End));
			} else {
				res.data.ResultMsg[index].Qty = 1;
			}
			if (barCodeRelus.BarRule_CutNum_Demical != "") {
				var temp = 10;
				for (var i in barCodeRelus.BarRule_CutNum_Demical) {
					temp *= 10;
				}
				res.data.ResultMsg[index].Qty /= temp;
			}
			if (barCodeRelus.BarRule_CutPrice_Start != "" && barCodeRelus.BarRule_CutPrice_End != "" &&
				parseInt(barCodeRelus.BarRule_CutPrice_Start) <= parseInt(barCodeRelus.BarRule_CutPrice_End)) {
				res.data.ResultMsg[index].Price = searchKey.substring(parseInt(barCodeRelus.BarRule_CutPrice_Start) - 1,
					parseInt(barCodeRelus.BarRule_CutPrice_End));
			} else {
				resultObj.isChange = false;
			}
			if (barCodeRelus.BarRule_CutPrice_Demical != "") {
				var temp = 10;
				for (var i in barCodeRelus.BarRule_CutPrice_Demical) {
					temp *= 10;
				}
				res.data.ResultMsg[index].Price /= temp;
			}
		} else {
			res.data.ResultMsg[index].Qty = 1;
			resultObj.isChange = false;
		}
	} else {
		res.data.ResultMsg[index].Qty = 1;
		resultObj.isChange = false;
	}
	resultObj.result = res;

	return resultObj;
	// console.log(res);
}
export function print(mac_address, item, BillType = 1, headerList, containerList, footerList) {

	console.log(containerList)
	console.log(footerList)
	// printConfigList
	// console.log(datas[data.name]);
	console.log("mac_address:" + mac_address);
	if (!mac_address) {
		mui.toast('请选择蓝牙打印机');
		return;
	}
	var device = null,
		BAdapter = null,
		BluetoothAdapter = null,
		uuid = null,
		main = null,
		that = this,
		bluetoothSocket = null;
	main = plus.android.runtimeMainActivity();
	BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
	var UUID = plus.android.importClass("java.util.UUID");
	uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	BAdapter = BluetoothAdapter.getDefaultAdapter();
	device = BAdapter.getRemoteDevice(mac_address);
	plus.android.importClass(device);
	bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
	plus.android.importClass(bluetoothSocket);
	if (!bluetoothSocket.isConnected()) {
		console.log('检测到设备未连接，尝试连接....');
		bluetoothSocket.connect();
	}
	console.log('设备已连接', bluetoothSocket.isConnected());
	if (!bluetoothSocket.isConnected()) {
		bluetoothSocket.connect();
	}
	if (bluetoothSocket.isConnected()) {
		console.log('设备已连接1');
		var outputStream = bluetoothSocket.getOutputStream();
		plus.android.importClass(outputStream);
		//var buffer = "打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试打印测试\r\n";  
		var printerJobs = new PrinterJobs();
		var esc = "打印测试\r\n";
		let Save_M_Data_Json = item.Save_M_Data_Json;
		let Save_D_Data_Json = item.Save_D_Data_Json;
		let Amount = 0;
		let AllQty = 0;
		Save_D_Data_Json.forEach((item, index) => {
			Amount = parseFloat(Amount) + parseFloat(item.Amount);
			AllQty = parseFloat(AllQty) + parseFloat(item.Qty);
			item.Qty = Math.round(item.Qty * 100) / 100 + "";
			item.DiscountPrice = Math.round(item.DiscountPrice * 100) / 100 + "";
			item.Amount = Math.round(item.Amount * 100) / 100 + "";
		})
		let headerSelect = printConfigList.printConfigList[BillType - 1].headerAndFoodCN;
		let containerSelList = printConfigList.printConfigList[BillType - 1].containtCn;
		headerList.forEach((item, index) => {
			headerSelect.forEach(($item, $index) => {
				if ($item.name == item.DataName) {
					printerJobs.print(item.LabText + ":" + Save_M_Data_Json[$item.key]);
					return;
				}
			})
		});

		printerJobs
			.setLineSpacing(1)
			.print(printerUtil.fillLine())
			.setLineSpacing()
			.setAlign('lt');
		let titleStr = "";
		containerList.forEach((item, index) => {
			containerSelList.forEach(($item, $index) => {
				if ($item.name == item.DataName) {
					titleStr += item.LabText;
					if (item.Y == "") {
						item.Y = 0;
					}
					for (var j = 0; j < item.Y; j++) {
						titleStr += ' ';
					}
					return;
				}
			});
		});
		printerJobs.print(titleStr);
		Save_D_Data_Json.forEach((items, indexs) => {
			titleStr = "";
			containerList.forEach((item, index) => {
				containerSelList.forEach(($item, $index) => {
					if ($item.name == item.DataName) {
						titleStr += items[$item.key];
						if (item.Y == "") {
							item.Y = 0;
						}
						for (var j = 0; j < item.Y; j++) {
							titleStr += ' ';
						}
						return;
					}
				});
			});
			printerJobs.print(titleStr);
		});
		printerJobs.print(printerUtil.fillLine())
			// .print(printerUtil.fillLine())
			// .print()
			.print("总数量:" + AllQty)
			.print("总金额:" + Amount).println().println();
		let buffer = printerJobs.buffer();
		var buffer1 = plus.android.invoke(esc, 'getBytes', 'gbk');
		const maxChunk = 256;
		const delay = 20;
		var length = 0;
		for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
			let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
			let array = Array.prototype.slice.call(new Int8Array(subPackage));
			outputStream.write(array)
		}

		//outputStream.write(buffer);  
		outputStream.flush();
		device = null; //这里关键  
		bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误  
	}
}
